package com.stackandqueue;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

public class SlidingWindowMaximum0204_239 {
    Deque<Integer> que;
    int[] res;
    public int[] maxSlidingWindow(int[] nums, int k) {
        res = new int[nums.length - k + 1];
        que = new LinkedList<>();

        for (int i = 0; i < k; i++) {
            PushElem(que, nums[i]);
        }
        res[0] = GetMax(que);

        for (int i = k; i < nums.length; i++) {
            PopElem(que, nums[i-k]);
            PushElem(que,nums[i]);
            res[i-k+1] = GetMax(que);

        }

        return res;

    }

    private int GetMax(Deque<Integer> que) {
        return que.peek();
    }

    private void PopElem(Deque<Integer> que, int num) {
        if(!que.isEmpty() && que.peek() == num) que.poll();
    }

    private void PushElem(Deque<Integer> que, int num) {
        while (!que.isEmpty() && que.getLast() < num){
            que.removeLast();
        }
        que.offer(num);
    }
}
